package org.adl.registry.types;

/**
 *
 * @author Jacob Marks - Joint ADL Co-Lab
 * @version 1.0
 * @license This software is licensed as open source software pursuant to the terms defined in the Joint ADL Co-Lab Open Source Software License.  Use of any part of this software constitutes acceptance of this license. The Joint ADL Co-Lab open source agreement is available at {@link http://adlregistry.adlnet.gov/source_license.html}.
 */
public class Username extends RimParameter
{
    public static final String OR_USER_HANDLE_NAMESPACE = "100.3.usr";
    public static final String PR_USER_HANDLE_NAMESPACE = "4444.usr";
    
    /**
     * Creates a new instance of Username
     * @param value
     */
    public Username(String iValue)
    {
        super("userid", iValue);
        
        this.validate();
    }
    
    protected void validate()
    {
        String value = super.getParameterValue();
        
        if (value == null)
        {
            super.getValidaionErrors().add("The provided username is invalid. A username must be at least one character in length excluding whitespace.");
        }
        else
        {
            if (value.contains(Handle.HANDLE_SEPERATOR))
            {
                char[] characters = value.toCharArray();
                
                boolean handleSeperatorFound = false;
                
                for (int i = 0; i < characters.length; i++)
                {
                    char character = characters[i];
                    
                    if (character == Handle.HANDLE_SEPERATOR.charAt(0))
                    {
                        if (handleSeperatorFound)
                        {
                            super.getValidaionErrors().add("The provided username contains a handle seperator but does not conform to valid handle syntax. A handle cannot contain more than one handle seperator.");
                        }
                        
                        handleSeperatorFound = true;
                    }
                }
                
                value = this.stripNamespace();
            }
            
            value.trim();
            
            if (value.length() == 0)
            {
                super.getValidaionErrors().add("The provided username is invalid. A username must be at least one character in length excluding whitespace.");
            }
        }
        
        if (super.isParameterValueValid())
        {
            super.setParameterValue(value);
        }
    }
    
    private String stripNamespace()
    {
        String striped = "";
        
        String value = super.getParameterValue();
        
        String[] parts = value.split(Handle.HANDLE_SEPERATOR);
        
        striped = parts[1];
        
        return striped;
    }
}
